package strategy;

import windows.MainWindow;
import core.Data;

public class C36 implements AlgorithmInteface {

	private byte[][] sMatrix;
	private byte[][] mMatrix;
	private String text;
	private String result;
	private MainWindow ref;
	private char[] abc;
	
	private byte[] oneCount;
	
	public C36(String text, MainWindow reference) {
		ref = reference;
		sMatrix = Data.getInstance().getsMatrix();
		mMatrix = Data.getInstance().getmMatrix();
		this.text = text;
		text = text.toLowerCase();
		result = "";
		oneCount = new byte[27];
		abc = Crypto.ENG_ABC;
	}
	
	@Override
	public void decrypt() {
		for (int i = 0; i < text.length(); i++) {
			int count = 0;
			for (int j = 0; j < 6; j++) {
				if (sMatrix[j][i] == 1) {
					for (int k = 0; k < 27; k++) {
						count += mMatrix[j][k];
					}
				}
			}
			int charPos = getPos(text.charAt(i));
			if (charPos != -1) {
				if ((count - charPos - 1) < 0) {
					result += abc[(abc.length + (count - charPos - 1)) % 26];
				} else {
					result += abc[(count - charPos - 1) % 26];
				}
			}
			else {
				result += text.charAt(i);
			}
//			result += abc[(count - getPos(text.charAt(i)) - 1 < 0) ?  abc.length + (count - getPos(text.charAt(i)) - 1) : (count - getPos(text.charAt(i)) - 1)];
		}
		update();
	}

	private int getPos(char c) {
		for (int i = 0; i < abc.length; i++) {
			if (abc[i] == c) {
				return i;
			}
		}
		return -1;
	}
	
	@Override
	public void encrypt() {
		for (int i = 0; i < text.length(); i++) {
			int count = 0;
			for (int j = 0; j < 6; j++) {
				if (sMatrix[j][i] == 1) {
					for (int k = 0; k < 27; k++) {
						count += mMatrix[j][k];
					}
				}
			}
			int charPos = getPos(text.charAt(i));
			if (charPos != -1) {
				if ((count - charPos - 1) < 0) {
					result += abc[(abc.length + (count - charPos - 1)) % 26];
				} else {
					result += abc[(count - charPos - 1) % 26];
				}
			}
			else {
				result += text.charAt(i);
			}
//			result += abc[(count - getPos(text.charAt(i)) - 1 < 0) ?  abc.length + (count - getPos(text.charAt(i)) - 1) : (count - getPos(text.charAt(i)) - 1)];
		}
		update();
	}

	@Override
	public void autoDecrypt() {
		// TODO Auto-generated method stub

	}

	@Override
	public void update() {
		ref.c36Update(result);
	}

}
